<?php
/**
 * 客服模块
 */
namespace app\admin\controller;

use think\Db;
use think\Request;
use think\Session;
use think\Config;
use think\Image;
use app\common\controller\AdminBase;
use app\common\util\WechatThirdUtil;
use app\common\model\Csuser as CsuserModel;
use app\common\model\AuthorWxUser as AuthorWxUserModel;
use app\common\model\WxUser as WxUserModel;
use app\common\model\Users as UsersModel;


class CustmSvc extends AdminBase
{
    protected $wechat_obj;
    protected $config;
    protected $third_config;
    protected $author_wx_user_model;
    protected $admin_id;
    protected $wx_user_model;
    protected $csuser_model;
    protected $users_model;

    protected function _initialize(){
        parent::_initialize();
        $this->csuser_model = new CsuserModel;
        $this->author_wx_user_model = new AuthorWxUserModel;
        $this->wx_user_model = new WxUserModel;
        $this->users_model = new UsersModel;
        $this->config = Session::get('wechat_info'); //当前授权公众号信息
        $this->third_config = $this->wx_user_model->find(); //第三方开发平台信息
        $this->wechat_obj = new WechatThirdUtil($this->third_config , $this->config);
    }

    public function index(){
        return $this->fetch();
    }

    public function add(){
        return $this->fetch();
    }

    public function edit(){
        return $this->fetch();
    }

    public function onlinecustlist(){
        return $this->fetch();
    }

    

    /**
     * 获取所有客服账号
     */
    public function queryCust(){
        
        $wechat_obj = $this->wechat_obj;
        $result = $wechat_obj->getCustAcNum();
        return json($result);
    }

    /**
     * 获取数据库客服账号
     */
    public function getCustomerServiceInfo(){
        $auid = $this->config['id'];
        $where = [
            'c.auid' => ['eq',$auid],
        ];
        //  , online_butt desc
       $result = $this->csuser_model->alias('c')->field('c.*,q.name')->where($where)->order('status desc , type asc')->join('think_qrcode q','q.scene_id = c.u_scene_id','LEFT')->select();
        return json($result);
    }

    /**
     * 获取在线客服客服列表
     */
    public function queryOnlineCust(){
        $wechat_obj = $this->wechat_obj;
        $result = $wechat_obj->getOnlineCustList();
        return json($result);
    }

    /**
     * 添加客服账号
     */
    public function addCust(){
        $data = $this->request->post();
        $wechat_obj = $this->wechat_obj;
        $wechat_info = $this->config;
        if($this->config['weixin'] == ''){
            return json(['status' => -1,'msg' => '未设置微信号']);
        }
        $validate_result = $this->validate($data, 'Csuser');
        if($validate_result !== true){
            $this->error($validate_result);
        }else{
            $customer_service_data = [
                'auid' => $wechat_info['id'], //公众号id
                'pid' => $data['pid'], //所属账号id
                'username' => $data['username'], //用户名
                'password' => $data['password'], //密码
                'nickname' => $data['nickname'], //昵称
                'header_url' => $data['img_path'],//头像
                'pa_pwd' => $data['password'], //明文密码
                'remark' => $data['remark'], //备注
            ];
            if($data['scene_id'] != '') $customer_service_data['u_scene_id'] = $data['scene_id'];
            $customer_service_data['password'] = md5($customer_service_data['password'] . Config::get('salt')); //密码
            if ($this->csuser_model->allowField(true)->save($customer_service_data)) {
                $this->config['create_cs_count'] = ++$this->config['create_cs_count'];
                Session::set('wechat_info',$this->config);
                M('author_wx_user')->where('id',$this->config['id'])->update(['create_cs_count' => $this->config['create_cs_count']]);
                $kfAccount = $data['username']."@{$this->config['weixin']}";
                $nickname = $data['nickname'];
                $result = $wechat_obj->createCustAcNum($kfAccount,$nickname);
                if($result && !empty($data['img_path'])){
                    $path = realpath('.'.$data['img_path']);
                    $res = $wechat_obj->uploadCustHeadImg($kfAccount,$path);  
                    return json($res);
                }else{
                    return json($result);
                }
            } else {
                $this->error('保存失败');
            }
        }
    }

    public function addCustNew(){
        $data = $this->request->post();
        $wechat_obj = $this->wechat_obj;
        $wechat_info = $this->config;
        if($this->config['weixin'] == ''){
            return json(['status' => -1,'msg' => '未设置微信号']);
        }
        $validate_result = $this->validate($data, 'Csuser');
        if($validate_result !== true){
            $this->error($validate_result);
        }else{
            $customer_service_data = [
                'auid' => $wechat_info['id'], //公众号id
                'pid' => $data['pid'], //所属账号id
                'username' => $data['username'], //用户名
                'password' => $data['password'], //密码
                'nickname' => $data['nickname'], //昵称
                'header_url' => $data['img_path'],//头像
                'pa_pwd' => $data['password'], //明文密码
                'remark' => $data['remark'], //备注
            ];
            if($data['scene_id'] != '') $customer_service_data['u_scene_id'] = $data['scene_id'];
            $customer_service_data['password'] = md5($customer_service_data['password'] . Config::get('salt')); //密码
            $save_csuser  =  $this->csuser_model->allowField(true)->insertGetId($customer_service_data);
//            Db::insertGetId();
            if ($save_csuser) {
                $this->config['create_cs_count'] = ++$this->config['create_cs_count'];
                Session::set('wechat_info',$this->config);
                M('author_wx_user')->where('id',$this->config['id'])->update(['create_cs_count' => $this->config['create_cs_count']]);
                $kfAccount = $data['username']."@{$this->config['weixin']}";
                $nickname = $data['nickname'];
                $result = $wechat_obj->createCustAcNum($kfAccount,$nickname);
                if($result && !empty($data['img_path'])){
                    $path = realpath('.'.$data['img_path']);
                    $res = $wechat_obj->uploadCustHeadImg($kfAccount,$path);
                    return json($res);
                }else{
                    return json([
                        'data' => $result,
                        'csid' => $save_csuser
                    ]);
                }
            } else {
                $this->error('保存失败');
            }
        }
    }

    public function inserGid(){
        $wechat_info = $this->config;
        $customer_service_data = [
            'auid' => $wechat_info['id'], //公众号id
            'pid' => 0, //所属账号id
            'username' => 'h'.time(), //用户名
            'password' =>md5('123456' . Config::get('salt')), //密码
            'nickname' => 'hellokitty', //昵称
            'header_url' => '',//头像
            'pa_pwd' => '123456', //明文密码
            'remark' => 'hello', //备注
        ];
        $save_csuser  =  $this->csuser_model->allowField(true)->insertGetId($customer_service_data);
        var_dump($save_csuser);
    }

    /**
     * 组长列表
     */
    public function getPersonCustom(){
        $auid = $this->config['id'];
        $result = $this->csuser_model->field('id,nickname')->where('pid',0)->where('auid',$auid)->select();
        return json(['cs_list' => $result]);
    }

    /**
     * 邀请绑定客服帐号
     */
    public function InviteBindCust(){
        $data = $this->request->post();
        $wechat_obj = $this->wechat_obj;
        $kfAccount = $data['username']."@{$this->config['weixin']}";
        $wechatNum = $data['wechat_num'];
        $result = $wechat_obj->iniviteBindCustAcNum($kfAccount,$wechatNum);
        return json($result);
    }

    /**
     * 修改客服信息
     */
    public function updateCust(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $validate_result = $this->validate($data, 'Csuser.edit');
            if($validate_result !== true){
                $this->error($validate_result);
            } else {
                //注释是判断旧密码是否正确
                // if(!empty($data['old_password'])){
                    // if(!($customer = $this->csuser_model->where('username',$data['username'])->where('password',md5($data['old_password'] . Config::get('salt')))->find())){
                    //     return json(['status' => -1,'msg' => '旧密码不正确']);
                    // }
                // }else{
                    if(!($customer = $this->csuser_model->where('username',$data['username'])->find())){
                        return json(['status' => -1,'msg' => '账户不存在']);
                    }
                // }

                if(!empty($data['password']) && !empty($data['confirm_password']) && $data['password'] === $data['confirm_password']){
                    $customer->password = md5($data['password'] . Config::get('salt'));
                }
                
                $customer->nickname = $data['nickname'];
                $customer->header_url = $data['img_path'];
                if($customer->save() !== false){
                    $wechat_obj = $this->wechat_obj;
                    $kfAccount = $data['username']."@{$this->config['weixin']}";
                    $nickname = $data['nickname'];
                    $result = $wechat_obj->updateCustAcNum($kfAccount,$nickname);
                    if($result && !empty($data['img_path'])){
                        $path = realpath('.'.$data['img_path']);
                        $res = $wechat_obj->uploadCustHeadImg($kfAccount,$path);  
                        return json($res);
                    } else {
                        return json($result);
                    }
                } else {
                    return json(['status' => -1,'msg' => '保存失败']);
                }

            }
        }else{
            return json(['status' => -1,'msg' => '错误']);
        }
    }

    /**
     * 删除客服帐号
     */
    public function deleteCust(){
        $data = $this->request->get();
        $result = $this->csuser_model->save(['status' => 0],['username' => $data['username']]);
        if($result){
            $this->config['create_cs_count'] = --$this->config['create_cs_count'];
            if($this->config['create_cs_count'] < 0){
                $this->config['create_cs_count'] = 0;
            }
            Session::set('wechat_info',$this->config);
            M('author_wx_user')->where('id',$this->config['id'])->update(['create_cs_count' => $this->config['create_cs_count']]);
            $wechat_obj = $this->wechat_obj;
            $kfAccount = $data['username']."@{$this->config['weixin']}";
            $result = $wechat_obj->deleteCustAcNum($kfAccount);
            return json($result);
        }else{
            return json(['msg'=>'删除失败']);
        }
    }

    /**
     * 设置客服帐号的头像
     */
    public function setCustHeader(){
        $data = $this->request->post();
        $kfAccount = $data['username']."@{$this->config['weixin']}";
        $path = realpath('.'.$data['img_path']);
        $wechat_obj = $this->wechat_obj;
        $result = $wechat_obj->uploadCustHeadImg($kfAccount,$path);
        return json($result);
    }

    /**
     * 获取微信自带聊天记录
     */
    public function getCusmChatReord(){
        $start_time = strtotime(date('Y-m-d'));
        $end_time = mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
        $wechat_obj = $this->wechat_obj;
        $result = $wechat_obj->getWhatRecord($start_time,$end_time,$msgid = 1,$number = 10000);
        $recordArr = [];
        foreach($result['recordlist'] as $v){
            $recordArr[$v['openid']][] = $v;
        }
        // unset($recordArr['[unknown worker]']);

        $recombineArr = [];
        foreach($recordArr as $ko=>$vo){
            foreach($vo as $vs){
                // dump($vs);
                $recombineArr[$ko][$vs['worker']][] = $vs; 
            }
        }
        // dump($recombineArr);
        return json($recombineArr);
    }

    /**
     * 获取客服服务器聊天记录
     */
    public function getCusmChatList($cs_id){

    }


    public function test(){
        $wechat_obj = $this->wechat_obj;
        $result = $wechat_obj->getOnlineCustList();
        dump($result);
    }

    /**
     * 开启/关闭客服
     */
    public function isEnable($id,$status){
        $result = $this->csuser_model->save(['status' => $status],['id' => $id]);
        if($result){
            $arr_data = [
                'type' => 'current_csuser_count',
                'data' => [
                    'id' => $this->config['id'],
                    'uid' => $this->config['uid'],
                ],
            ];
            // 发送websocket 信息
            sendWebSocket($arr_data);
            return json(['status' => 1,'msg' => '修改成功',$arr_data]);
        } 
        return json(['status' => -1,'msg' => '修改失败']);
    }

    public function initServerPassword(){
        $auid = $this->config['id'];
        $result = $this->csuser_model->save(['password' => md5('123456' . Config::get('salt'))],['auid' => $auid]);
        if($result){
            return json(['status' => 1, 'msg' => '初始化成功']);
        }else{
            return json(['status' => -1, 'msg' => '初始化失败']);
        }
    }

    public function syncChatMsg(){
        $auid = $this->config['id'];
        $users = $this->users_model->where('auid',$auid)->column('openid');
        foreach($users as $openid){
            $cs_id = Db::connect('db_config_chatlog')->name('chatlog')->where('openid',$openid)->value('cs_id');
            if($cs_id){
                $result = $this->users_model->save(['butt_id' => $cs_id],['openid' => $openid]);
            }
        }
        return json(['status' => 1 , 'msg' => '已同步']);
    }

    // 设置离线回复
    public function reply($id){
        $result = $this->csuser_model->field('auto_reply_text,auto_reply_img')->where('id',$id)->find();
        $this->assign('reply_info',$result);
        return $this->fetch();
    }

    // 保存离线回复
    public function saveReply($id){
        if($this->request->isPost()){
            $data = $this->request->post();
            $auto_reply_img = $this->csuser_model->where('id',$id)->value('auto_reply_img');
            if($auto_reply_img != $data['auto_reply_img'] && !empty($data['auto_reply_img'])){
                //图片非空应上传到微信资源
                $chatImg = $this->wechat_obj->uploadMaterial('.'.$data['auto_reply_img'],'image');
                if($chatImg){
                    $data['auto_reply_img_media_id'] = $chatImg['media_id'];
                }
            }
            $result = $this->csuser_model->save($data,['id'=>$id]);
            if($result){
                return json(['status' => 1 , 'msg' => '保存成功']);
            }else{
                return json(['status' => -1 , 'error' => '保存失败']);
            }
        }
    }

    public function setRemarkMsg(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $result = $this->csuser_model->save(['remark' => $data['remark']],['id'=>$data['id']]);
            if($result){
                return json(['status' => 1 , 'msg' => 'ok']);
            }else{
                return json(['status' => -1 , 'error' => 'update error']);
            }
        }
    }

    public function poster($id){
        $poster = $this->csuser_model->field('id,auid,poster')->where('id',$id)->find();
        $this->assign('poster',$poster);
        return $this->fetch();
    }

    public function savePoster($id){
        if($this->request->isPost()){
            $data = $this->request->post();
            $x = $data['x'];
            $y = $data['y'];
            $image = Image::open('.'.$data['poster']);
            $image->water('.'.$data['qrcode'],[$x,$y])->save('.'.$data['qrcode']);
            $resoure = $this->wechat_obj->uploadMaterial('.'.$data['qrcode'], $type = 'image');
            if($resoure){
                $resoure_data = [
                    'poster' => $data['qrcode'],
                    'poster_media_id' => $resoure['media_id'],
                    'poster_url' => $resoure['url'],
                ];
                $result = $this->csuser_model->save($resoure_data,['id'=>$id]);
                if($result){
                    return json(['status' => 1 , 'msg' => '保存成功']);
                }else{
                    return json(['status' => -1 , 'error' => '保存失败']);
                }
            }
        }
    }

    public function delPoster($id){
        $data = [
            'poster' => '',
            'poster_media_id' => '',
            'poster_url' => ''
        ];
        $result = $this->csuser_model->save($data,['id' => $id]);
        if($result){
            return json(['status' => 1 , 'msg' => 'ok']);
        }else{
            return json(['status' => -1 , 'error' => 'delete poster error']);
        }
    }

    /*
     * 批量新建海草账号, 带离线回复
     * */

    public function manyFasion(){
        return $this->fetch("many");
    }

    /*
     * 保存新建的海草账号
     */
    public function saveFasion(){
        var_dump(Request::instance()->post());
    }

}